﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Se.Framework.Common;
using Se.Framework.Common.Data;
using Se.Framework.Web.Mvc.Filters;

namespace Se.Framework.Web.Mvc
{

    //http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options

    [UnitOfWorkManagementFilter]
    public abstract class ApiControllerBase<TEntity> : ApiController
        where TEntity : class
    {
        private readonly Lazy<IBusinessLayer<TEntity>> businessLayerLazy = ObjectRegistry.Current.ResolveLazy<IBusinessLayer<TEntity>>();

        protected IBusinessLayer<TEntity> BusinessLayer
        {
            get
            {
                return businessLayerLazy.Value;
            }
        }

        [UnitOfWorkProperties(AutoCommitEnable = false)]
        [Queryable]
        public virtual IQueryable Get()
        {
            return BusinessLayer.GetItems();
        }

        public virtual HttpResponseMessage Post(TEntity item)
        {
            BusinessLayer.AddItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }

        public virtual HttpResponseMessage Put(TEntity item)
        {
            BusinessLayer.UpdateItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }

        public virtual HttpResponseMessage Delete(TEntity item)
        {
            BusinessLayer.DeleteItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }
    }

    [UnitOfWorkManagementFilter]
    public abstract class ApiControllerBase<TIBusinessLayer, TEntity> : ApiController
        where TEntity : class
        where TIBusinessLayer : class, IBusinessLayer<TEntity>
    {
        private readonly Lazy<TIBusinessLayer> businessLayerLazy = ObjectRegistry.Current.ResolveLazy<TIBusinessLayer>();

        protected TIBusinessLayer BusinessLayer
        {
            get
            {
                return businessLayerLazy.Value;
            }
        }

        [UnitOfWorkProperties(AutoCommitEnable = false)]
        [Queryable]
        public virtual IQueryable Get()
        {
            return BusinessLayer.GetItems();
        }

        public virtual HttpResponseMessage Post(TEntity item)
        {
            BusinessLayer.AddItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }

        public virtual HttpResponseMessage Put(TEntity item)
        {
            BusinessLayer.UpdateItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }

        public virtual HttpResponseMessage Delete(TEntity item)
        {
            BusinessLayer.DeleteItem(item);
            return Request.CreateResponse(HttpStatusCode.OK, item);
        }
    }
}
